#include "frm_free_exercise.h"
#include "ui_frm_free_exercise.h"
#include "frm_menu.h"
#include "frm_free_exercise_doit.h"
#include <QFile>
#include <QTextStream>
#include <QString>
#include <QVector>
#include <QDesktopWidget>
#include <QDebug>

frm_free_exercise::frm_free_exercise(QDialog *parent) :
    QDialog(parent),
    ui(new Ui::frm_free_exercise)
{
    ui->setupUi(this);
    setWindowFlags( Qt:: WindowTitleHint | Qt:: CustomizeWindowHint | Qt:: WindowMinimizeButtonHint | Qt:: WindowMaximizeButtonHint);
    this->move(QApplication::desktop()->screen()->rect().center() - this->rect().center());
    QFile exercisesFile("exercises.txt");
    if(!exercisesFile.open(QIODevice::ReadOnly))
        qFatal("Can't open exercises.txt");

    QTextStream in(&exercisesFile);
    QString exercise;
    QString i;
    while(!in.atEnd()){
        exercise = in.readLine();
        QListWidgetItem *item = new QListWidgetItem(exercise);
        i = in.readLine(); //leemos imagen
        item->setIcon( QIcon(i));
        ui->exerciseslist->addItem(item);
    }
}

frm_free_exercise::~frm_free_exercise()
{
    delete ui;
}

void frm_free_exercise::on_btn_back_clicked()
{
    frm_menu *menu = new frm_menu();
    this->hide();
    menu->show();
}

void frm_free_exercise::on_btn_doit_clicked()
{
    QString exerfilename = ui->exerciseslist->currentItem()->text()+".txt";
    QFile exerfile(exerfilename);
    if(!exerfile.open(QIODevice::ReadOnly))
        qFatal("Can't open this exercise file");
    QTextStream in(&exerfile);
    QVector<QString> data(4);
    QString dato;
    int i = 0;
    while (!in.atEnd()){
        dato = in.readLine();
        if (dato != "")
            if (i == 1 || i == 3)
                data[i]= dato;
            else
                data[i] = data[i] + "\n" + dato;
        else
            i++;
        }

    //data[1] = in.readLine();
    //data[2] = in.readLine();
    //data[3] = in.readLine();
    frm_free_exercise_doit *doit = new frm_free_exercise_doit(ui->exerciseslist->currentItem()->text(),data[0],data[1],data[2],data[3]);
    //qDebug()<<ui->exerciseslist->currentItem()->text()<<endl<<endl<<data[0]<<endl<<endl<<data[1]<<endl<<endl<<data[3]<<endl<<endl<<data[4];
    this->hide();
    doit->show();
}
